const api = require("../../../utils/marketAPIUtils");
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    loadLock:true,
    clickLock:false,
    note:null,
    addressInfo:{
        id:0,
        address:'请选择收货地址'
    },
    moneyScope:{},
    applyId:null,
    logisticsType:2
  },

  /**
   * 从缓存中加载商品
   */
  _loadGoodsByStore(applyId,specificationId,goodsNum,buyType,callback){
    try {
      var value = wx.getStorageSync(app.globalData.ks_buyGoods);
      if (value) {
        var specificationName = null;
        if(specificationId){
          for(var i=0;i<value.specifications.length;i++){
            var item = value.specifications[i];
            if(item.id == specificationId){
              specificationName = item.name;
              break;
            }
          }
        }
        var logisticsType = this.data.logisticsType;
        if(value.classify == 2){
            logisticsType = 3;
        }

        this.setData({
          goods:value,
          goodsNum:goodsNum,
          buyType:buyType,
          specificationId:specificationId,
          specificationName:specificationName,
          applyId:applyId,
          logisticsType:logisticsType
        })
        if(callback){
          console.log("加载商品信息后回调")
          callback.call(this);
        }
      }else{
        wx.hideLoading();
      }
    } catch (e) {}
  },

  //获取配送费
  _findLogisticsCostList:function(addressId,supplierId){
    var self = this;
    api.post(api.url.findLogisticsCostList,{
      addressId:addressId,
      supplierId:supplierId
    },function(res){
      console.log(res.data);
      var logisticsCostList = [];
      if(res.data.code == 200){
        for(var i=0;i<res.data.body.items.length;i++){
          var item = res.data.body.items[i];
           var name = item.name;
           if(item.money > 0){
            name = name + '（' + item.money + '元）';
           }else{
               name = name + '（包邮）';
           }

          logisticsCostList.push({
            id:item.companyId,
            name:name,
            subname:item.note
          })
        }
      }

      var changeLogistics = 2; 
      if(logisticsCostList.length > 1){
        changeLogistics = 1;
      }
      self.setData({
        logisticsCostList:logisticsCostList,
        changeLogistics:changeLogistics
      })
    });
  },

  /**
   * 切换价格
   */
  _changeMoney(callback){
    var self = this;
    var addressId = this.data.addressInfo.id;
    var goodsId = this.data.goods.goodsId;
    var logisticsCompanyId = this.data.logisticsCompanyId;
    var goodsNum = this.data.goodsNum;
    var buyType = this.data.buyType;
    var moneyScope = this.data.moneyScope;
    api.post(api.url.goodsPayCheck,{
      goodsId:goodsId,
      goodsNum:goodsNum,
      addressId:addressId,
      buyType:buyType,
      virtualMoney:moneyScope.virtualMoney,
      walletMoney:moneyScope.walletMoney,
      logisticsCompanyId:logisticsCompanyId
    },function(res){
      console.log(res);
      //先调用回调函数，关闭加载提示
      if(callback){
        callback.call();
      }
      if(res.data.code == 200){
        var goods = self.data.goods;
        if(self.data.buyType == 2){
          goods.teamPayMoney = res.data.body.goodsMoney;
        }else {
          goods.payMoney = res.data.body.goodsMoney;
        }
        var addressId = null;
        var addressInfo = self.data.addressInfo;
        if(res.data.body.address){
          addressInfo = res.data.body.address;
        } 
        if(addressInfo){
          addressId = addressInfo.id;
        }
        if(!self.data.logisticsCostList){
           //self._findLogisticsCostList(addressId,supplierId);
        }
   
        var express = self.data.express;
        if(res.data.body.logistics){
          express = res.data.body.logistics.name + " " + res.data.body.logistics.money;
          if(res.data.body.logistics.companyId){
            logisticsCompanyId = res.data.body.logistics.companyId;
          }
        }

        self.setData({
          moneyScope:res.data.body,
          goods:goods,
          addressInfo:addressInfo,
          express : express,
          logisticsCompanyId:logisticsCompanyId
        })
      }else if(res.data.msg){
        wx.showModal({
            title: '温馨提示',
            content: res.data.msg,
            showCancel: false,
            complete:function(){
                wx.hideLoading();
                //wx.navigateBack();
            }
        })
      }else{
        wx.showToast({
            title: '获取价格失败'
        })
        setTimeout(() => {
            wx.hideLoading();
            //wx.navigateBack();
        }, 1000);
        return;
      }
    },function(){
        wx.hideLoading();
        //wx.navigateBack();
    })
  },

  _goodsPay:function(){
    var tradeNo = this.data.tradeNo;
    var goodsId = this.data.goods.goodsId;
    var goodsNum = this.data.goodsNum;
    var specificationId = this.data.specificationId;
    var moneyScope = this.data.moneyScope;
    var self = this;
    api.post(api.url.goodsPay,{
      tradeNo:tradeNo,
      goodsId:goodsId,
      goodsNum:goodsNum,
      specificationId:specificationId,
      virtualMoney:moneyScope.virtualMoney,
      walletMoney:moneyScope.walletMoney,
      payMoney:moneyScope.payMoney,
      appId:wx.getAccountInfoSync().miniProgram.appId,
      payType:3,
      note:this.data.note,
      addressId:this.data.addressInfo.id,
      logisticsCompanyId:this.data.logisticsCompanyId,
      couponId:null
    },function(res){
      wx.hideLoading();
      self.data.clickLock = false;
      console.log(res.data);
      if(res.data.code == 200){
        var tradeNo = res.data.body.tradeNo;
        self.setData({
          tradeNo:tradeNo
        });
        var payInfo = JSON.parse(res.data.body.payInfo);
        wx.requestPayment({
          appId: payInfo.appId,
          timeStamp: payInfo.timeStamp + "",
          nonceStr: payInfo.nonceStr,
          package: payInfo.package,
          signType: payInfo.signType,
          paySign: payInfo.sign,
          success(res) {
            console.log('支付成功');
            wx.redirectTo({
              url: '../order/info?tradeNo='+tradeNo
            });
          }
          , fail(res) {
            console.log(res);
            wx.hideLoading();
          }
        });
      }else if(res.data.code == 801){
        var tradeNo = res.data.body.tradeNo;
        wx.showModal({
            title: '温馨提示',
            content: '支付成功',
            success:function (res) {
                if(res.confirm){
                    wx.redirectTo({
                        url: '../order/info?tradeNo='+tradeNo
                    });
                }
            }
        })
      }else if(res.data.code == 802){
        var tradeNo = res.data.body.tradeNo;
        wx.showModal({
            title: '温馨提示',
            content: '该商品有未支付订单，请优先使用',
            success:function (res) {
                if(res.confirm){
                    wx.redirectTo({
                        url: '../order/info?tradeNo='+tradeNo
                    });
                }
            }
        })
      }else if(res.data.code == 800){
        wx.redirectTo({
          url: './info?goodsId='+goodsId
        });
      }else {
        wx.showModal({
            title: '温馨提示',
            content: '购买失败，请稍后再试',
            showCancel: false
        })
      }
    });
  },

  onMoneyInput:function(e){
    var key = e.currentTarget.dataset.id;
    var moneyScope = this.data.moneyScope;
    if(key == 'virtualMoney'){
        if(e.detail.value > 999){
            moneyScope[key] = e.detail.value;
        }else{
            return;
        }
    }else{
        moneyScope[key] = e.detail.value;
    }
    if(!this.data.loadLock){
        this.data.loadLock = true;
        var _self = this;
        this._changeMoney(function(){
            _self.data.loadLock = false;
        });
    }
  },

  onInputNote:function(e){
      this.data.note = e.detail.value;
  },

  onVirtualBlur:function(e){
    if(e.detail.value < 999){
        var moneyScope = this.data.moneyScope;
        moneyScope['virtualMoney'] = 0;
        this.setData({
            moneyScope:moneyScope
        })
    }
  },

  btnUpdateGoodsNum:function(e){
    let type = e.currentTarget.dataset.type;
    if('add' == type){
        let goodsNum = parseInt(this.data.goodsNum);
        this.setData({
            goodsNum:goodsNum + 1
        })
    }else if('move' == type){
        let goodsNum = parseInt(this.data.goodsNum);
        if(goodsNum > 1){
            this.setData({
                goodsNum:goodsNum - 1
            })
        }
    }
    //重新计算价格
    this._changeMoney(function(){
        //---
    })
  },

  btnPayJoin:function(){
    if(utils.isRepeat()){return;}

    if(!this.data.addressInfo.id){
      wx.showToast({
        icon:'error',
        title: '请选择收货地址',
      })
      return;
    }

    utils.showLoading();
    var self = this;
    var goodsId = this.data.goods.goodsId;
    var goodsNum = this.data.goodsNum;
    var applyId = this.data.applyId;
    var tradeNo = this.data.tradeNo;
    var specificationId = this.data.specificationId;
    api.post(api.url.simpleApplyPayJoin,{
      applyId:applyId,
      tradeNo:tradeNo,
      goodsId:goodsId,
      goodsNum:goodsNum,
      appId:wx.getAccountInfoSync().miniProgram.appId,
      payType:3,
      addressId:this.data.addressInfo.id,
      specificationId:specificationId,
      couponId:null
    },function(res){
      utils.hideLoading();
      console.log(res.data);
      if(res.data.code == 200){
        var tradeNo = res.data.body.tradeNo;
        var applyId = res.data.body.applyId;
        self.setData({
          tradeNo:tradeNo,
          applyId:applyId
        });
        var payInfo = JSON.parse(res.data.body.payInfo);
        wx.requestPayment({
          appId: payInfo.appId,
          timeStamp: payInfo.timeStamp + "",
          nonceStr: payInfo.nonceStr,
          package: payInfo.package,
          signType: payInfo.signType,
          paySign: payInfo.sign,
          success(res) {
            console.log('支付成功');
            wx.redirectTo({
              url: '/pages/order/teamPayDetails?tradeNo='+tradeNo
            });
          }
          , fail(res) {
            console.log(res);
            wx.hideLoading();
          }
        });
      }else if(res.data.code == 800){
        wx.redirectTo({
          url: '/pages/goods/goods?id='+goodsId
        });
      }else {
        app.showErrorTips(res.data.msg,'团拼失败');
      }
    },function(res){
        console.log(res);
        utils.showErrorTips('网络繁忙');
    });
  },

  btnPay:function(){
    if(this.data.clickLock){return;}
    this.data.clickLock = true;
    
    if(this.data.goods.classify == 1){
        //实体
        if(!this.data.addressInfo.id){
            wx.showToast({
              icon:'error',
              title: '请选择收货地址',
            })
            this.data.clickLock = false;
            return;
        }
    }else{
        if(!this.data.note){
            wx.showToast({
                icon:'error',
                title: '请填写备注信息',
              })
              this.data.clickLock = false;
              return;
        }
    }

    wx.showLoading({
        title: '加载中...',
    })

    if(this.data.buyType == 2){
      this._teamPay();
    }else{
      this._goodsPay();
    }
  },

  /**
   * 切换收货地址
   */
  toChangeAddress:function(){
    var id = this.data.addressInfo.id;
    wx.navigateTo({
      url: './address?id='+id
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(!options){
        wx.showToast({
            title: '参数错误',
            icon:'error'
        })
        setTimeout(() => {
            wx.reLaunch({
                url: '../index/index',
            })
        }, 1000);
        return
    }
    wx.showLoading({
        title: '加载中...',
    })

    this.setData({
        payMoney:options.payMoney||0
    })
    var tradeNo = options.tradeNo;
    var self = this;
    if(tradeNo){
        this._loadGoodsByTradeNo(tradeNo,function(){
            this._changeMoney(function(){
                wx.hideLoading();
                self.data.loadLock = false;
            });
        });
    }else{
        var goodsNum = options.goodsNum;
        var buyType = options.buyType;
        var applyId = options.applyId || null;
        var specificationId = options.specificationId;
        this._loadGoodsByStore(applyId,specificationId,goodsNum,buyType,function(){
            //触发价格调整
            this._changeMoney(function(){
                wx.hideLoading();
                self.data.loadLock = false;
            });
        });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    try {
        var value = wx.getStorageSync(app.globalData.ks_buyAddress);
        if (value) {
            this.setData({
                addressInfo:value,
                logisticsCostList:null
            })
        }
    } catch (e) {}
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})